import React,{createContext, useContext} from 'react'
import { useLocation,useOutlet } from 'react-router-dom'
export interface KeepAliveProps {
    keepPath: string[]
}
const isKeepPath = (keepPath: string[], pathname: string) => {
    return keepPath.includes(pathname)
}
//用来缓存组件的对象
const keepElement: Record<string,any> = {}
const keepAliveContext = createContext({
    keepPath:[],
    keepElement,
    dropBypath(path:string){
        keepElement[path]=null
    }
})
export function useKeepAliveOutlet(){
    const location = useLocation()
    const element = useOutlet()
    const {keepElement,keepPath} = useContext(keepAliveContext)
    const isKeep = isKeepPath(keepPath,location.pathname)//当前展示的组件是否需要被缓存
    if(isKeep){
        keepElement[location.pathname]=element
    }
    return <>
    {
        Object.keys(keepElement).map(key=>{
            return <div key={key}>{keepElement[key]}</div>
        })
    }
    </>
}
export default function KeepAlive(props: KeepAliveProps) {
    const { keepPath } = props
    const {keepElement,dropBypath} = useContext(keepAliveContext)
    return (
        <keepAliveContext.Provider value={{keepPath,keepElement,dropBypath}}>
            
        </keepAliveContext.Provider>
    )
}
